package com.zhouzhou.fastjava.query.dialect;

import com.google.common.collect.Lists;
import com.zhouzhou.fastjava.query.*;
import com.zhouzhou.fastjava.util.CollectionKit;
import org.apache.commons.lang3.StringUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

/**
 * User: liuzheqiang
 * Date: 2017/12/28
 * Time: 17:31
 */
public abstract class Dialect {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public abstract String getQueryListSQL(String module, ColumnMapping columnMapping, String sql, ModuleQueryStatement mqStatement, QueryArgs args, List<QuerySortor> sortors);

    protected String getOrderSql(String module, ColumnMapping columnMapping, ModuleQueryStatement mqStatement, List<QuerySortor> sortors) {
        StringBuilder orderSql = new StringBuilder();
        if (CollectionKit.isNotEmpty(sortors)) {
            List<String> sortorStrs = Lists.newArrayList();
            for (QuerySortor sortor : sortors) {
                sortorStrs.add(" " + columnMapping.mapping(sortor.getProperty()) + " " + sortor.getDirection());
            }
            orderSql.append(" ORDER BY ").append(StringUtils.join(sortorStrs, ","));
        } else {
            QuerySetting querySetting = mqStatement.getQuerySetting();
            if (querySetting != null) {
                List<QuerySortor> defaultOrderBys = querySetting.getDefaultOrderBys();
                if (CollectionKit.isNotEmpty(defaultOrderBys)) {
                    List<String> orderStrs = defaultOrderBys.stream().map(orderBy -> columnMapping.mapping(orderBy.getProperty()) + " " + orderBy.getDirection().name()).collect(Collectors.toList());
                    orderSql.append(" ORDER BY ").append(StringUtils.join(orderStrs.toArray(new String[0]), ", "));
                }
            } else {
                logger.warn(module + "'s defaultOrderBy is null");
            }
        }
        return orderSql.toString();
    }

}
